package com.mbyte.easy.studentInfo.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mbyte.easy.qcbyclass.entity.QcbyClass;
import com.mbyte.easy.qcbyclass.service.IQcbyClassService;
import com.mbyte.easy.security.entity.SysUser;
import com.mbyte.easy.security.entity.SysUserRoles;
import com.mbyte.easy.security.service.ISysUserRolesService;
import com.mbyte.easy.security.service.IUserService;
import com.mbyte.easy.status.entity.Status;
import com.mbyte.easy.status.service.IStatusService;
import com.mbyte.easy.studentInfo.entity.TStudent;
import com.mbyte.easy.studentInfo.service.ITStudentService;
import com.mbyte.easy.common.controller.BaseController;
import com.mbyte.easy.common.web.AjaxResult;
import com.mbyte.easy.studentInfo.service.UploadService;
import com.mbyte.easy.util.PageInfo;
import com.mbyte.easy.util.Utility;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.time.LocalDate;
import java.time.LocalDateTime;

import static com.mbyte.easy.studentInfo.entity.ExcelUtil.readExcel;

/**
* <p>
* 前端控制器
* </p>
* @author lp
* @since 2019-03-11
*/
@Controller
@RequestMapping("/studentInfo/tStudent")
public class TStudentController extends BaseController  {

    private String prefix = "studentInfo/tStudent/";
    @Autowired
    private IQcbyClassService iQcbyClassService;
    @Autowired
    private IStatusService statusService;
    @Autowired
    private ITStudentService tStudentService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ISysUserRolesService sysUserRolesService;
    @Autowired
    UploadService uploadService;
    /**
    * 查询列表
    *
    * @param model
    * @param pageNo
    * @param pageSize
    * @param tStudent
    * @return
    */
    @RequestMapping
    public String index(Model model,@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                        @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize,
                        TStudent tStudent) {
        Page<TStudent> page = new Page<TStudent>(pageNo, pageSize);
        QueryWrapper<TStudent> queryWrapper = new QueryWrapper<TStudent>();
        if(!ObjectUtils.isEmpty(tStudent.getUserId())) {
            queryWrapper = queryWrapper.like("user_id",tStudent.getUserId());
         }
        if(!ObjectUtils.isEmpty(tStudent.getClassId())) {
            queryWrapper = queryWrapper.like("class_id",tStudent.getClassId());
         }
        if(!ObjectUtils.isEmpty(tStudent.getName())) {
            queryWrapper = queryWrapper.like("name",tStudent.getName());
         }
        if(!ObjectUtils.isEmpty(tStudent.getSex())) {
            queryWrapper = queryWrapper.like("sex",tStudent.getSex());
         }
        if(!ObjectUtils.isEmpty(tStudent.getAge())) {
            queryWrapper = queryWrapper.like("age",tStudent.getAge());
         }
        if(!ObjectUtils.isEmpty(tStudent.getPhone())) {
            queryWrapper = queryWrapper.like("phone",tStudent.getPhone());
         }
        if(!ObjectUtils.isEmpty(tStudent.getEmail())) {
            queryWrapper = queryWrapper.like("email",tStudent.getEmail());
         }
        IPage<TStudent> pageInfo = tStudentService.pageInfo(page, queryWrapper,tStudent);
        List<QcbyClass> classList = iQcbyClassService.list();
        List<Status> statusList = statusService.list();
        model.addAttribute("searchInfo", tStudent);
        model.addAttribute("classList", classList);
        model.addAttribute("statusList", statusList);
        model.addAttribute("pageInfo", new PageInfo(pageInfo));
        return prefix+"list";
    }

    /**
    * 添加跳转页面
    * @return
    */
    @GetMapping("addBefore")
    public String addBefore(Model model){
        List<QcbyClass> classList = iQcbyClassService.list();
        List<Status> statusList = statusService.list();
        model.addAttribute("classList", classList);
        model.addAttribute("statusList", statusList);
        return prefix+"add";
    }
    /**
    * 添加
    * @param tStudent
    * @return
    */
    @PostMapping("add")
    @ResponseBody
    public AjaxResult add(TStudent tStudent) {
        if(userService.selectByUsername(tStudent.getUsername()) != null){
            return  this.error("用户名重复！请重新输入！");
        }
        SysUser sysUser = new SysUser();
        sysUser.setSexType(tStudent.getSexType());
        sysUser.setUsername(tStudent.getUsername());
        sysUser.setPassword(Utility.QuickPassword(tStudent.getUsername()));
        sysUser.setCreatetime(new Date());
        sysUser.setUpdatetime(new Date());
        sysUser.setAvailable(true);
        userService.insert(sysUser);
        SysUser sysUser1 = userService.selectByUsername(tStudent.getUsername());
        SysUserRoles sysUserRoles = new SysUserRoles();
        sysUserRoles.setRolesId((long) 2);
        sysUserRoles.setSysUserId(sysUser1.getId());
        userService.insertuserRoles(sysUserRoles);
        tStudent.setUserId(sysUser1.getId());
        System.err.println(tStudent);
        return toAjax(tStudentService.save(tStudent));
    }
    /**
    * 添加跳转页面
    * @return
    */
    @GetMapping("editBefore/{id}")
    public String editBefore(Model model,@PathVariable("id")Long id){
        model.addAttribute("tStudent",tStudentService.getById(id));
        List<QcbyClass> classList = iQcbyClassService.list();
        List<Status> statusList = statusService.list();
        model.addAttribute("classList", classList);
        model.addAttribute("statusList", statusList);
        return prefix+"edit";
    }
    /**
    * 添加
    * @param tStudent
    * @return
    */
    @PostMapping("edit")
    @ResponseBody
    public AjaxResult edit(TStudent tStudent){
        return toAjax(tStudentService.updateById(tStudent));
    }
    /**
    * 删除
    * @param id
    * @return
    */
    @GetMapping("delete/{id}")
    @ResponseBody
    public AjaxResult delete(@PathVariable("id") Long id){
        TStudent byId = tStudentService.getById(id);
        if(userService.selectByPrimaryKey(byId.getUserId()) == null){
            return this.error(byId.getName()+"查无此人！请联系管理员！");
        }
        SysUserRoles sysUserRoles = sysUserRolesService.selectByUserId(id);

        userService.removeUser(byId.getUserId());
        return toAjax(tStudentService.removeById(id));
    }
    /**
    * 批量删除
    * @param ids
    * @return
    */
    @PostMapping("deleteAll")
    @ResponseBody
    public AjaxResult deleteAll(@RequestBody List<Long> ids){
        for (int i = 0; i < ids.size(); i++) {
            TStudent byId = tStudentService.getById(ids.get(i));
            if(userService.selectByPrimaryKey(byId.getUserId()) == null){
                return this.error(byId.getName()+"查无此人！请联系管理员！");
            }
            userService.removeUser(byId.getUserId());
        }
        return toAjax(tStudentService.removeByIds(ids));
    }
    /*
    *功能描述：通过表格批量添加学生
    *return：
    */
    @RequestMapping(value = "/add_file")
    @ResponseBody
    public JSONObject upload(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {
        System.err.println("-------------开始上传文件--------------");
        System.err.println(file);
        JSONObject object = new JSONObject();
        if(file != null) {
            System.err.println("-------------开始上传数据--------------");
            String savePath = request.getSession().getServletContext().getRealPath("/upload");
            // 获取文件扩展名
            String fileName = file.getOriginalFilename();
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            // 创建随机文件名，防止文件名重复
            fileName = randomFileName() + "." +fileType;
            System.out.println(fileName);
            File saveFile = new File(savePath, fileName);
            System.err.println(saveFile);
            if(!saveFile.getParentFile().exists()) {
                //创建文件夹[多级文件夹]file.madir是创建单一文件夹
                saveFile.getParentFile().mkdirs();
            }
            saveFile = new File(savePath, fileName);
            file.transferTo(saveFile);
            // 上传成功，返回带密码信息的excel文件
            List<List<String>>  result = readExcel(saveFile.getCanonicalPath());
            try {
                Integer last_result = uploadService.read(result);
            } catch (Exception e) {
                e.printStackTrace();
                object.put("code","1010");
                object.put("message",e.getMessage());
                return object;
            }
            System.err.println("-------------上传数据完毕--------------");
            object.put("code","200");
            object.put("message","添加成功!");
            return object;
        }
        object.put("code","1010");
        object.put("message","添加失败，文件为空！");
        return object;
    }
    public  String randomFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = simpleDateFormat.format(date);
        return fileName;
    }
}

